package solution1.demo1201.demo2;

import solution1.demo1201.demo2.request.LoginArguments;
import solution1.demo1201.demo2.request.LoginResponse;
import solution1.demo1201.demo2.request.Request;
import solution1.demo1201.demo2.request.Response;
import solution1.demo1201.demo2.tool.BinaryTool;

import java.io.*;
import java.net.Socket;

public class TCPClient {

    private Socket socket;
    private OutputStream outputStream;
    private InputStream inputStream;
    private DataInputStream dataInputStream;
    private DataOutputStream dataOutputStream;


    public TCPClient(String ip, int port) throws IOException {
        this.socket = new Socket(ip, port);
        this.outputStream = socket.getOutputStream();
        this.inputStream = socket.getInputStream();
        this.dataInputStream = new DataInputStream(inputStream);
        this.dataOutputStream = new DataOutputStream(outputStream);
    }

    /**
     * 发送请求
     * @param request
     * @throws IOException
     */
    public void sendRequest(Request request) throws IOException {
        dataOutputStream.writeInt(request.getType());
        dataOutputStream.writeInt(request.getLength());
        dataOutputStream.write(request.getBody());
        dataOutputStream.flush();
    }

    public Response getResponse() throws IOException {
        Response response = new Response();
        response.setType(dataInputStream.readInt());
        response.setLength(dataInputStream.readInt());
        byte[] payload = new byte[response.getLength()];
        int read = dataInputStream.read(payload);
        if(read != response.getLength()) {
            throw new RuntimeException("[TCPClient] 读取请求格式出粗");
        }
        response.setBody(payload);
        return response;
    }

    public boolean login(String username, String password) throws IOException {
        //1.准备请求
        LoginArguments loginArguments = new LoginArguments();
        loginArguments.setUsername(username);
        loginArguments.setPassword(password);
        byte[] payload = BinaryTool.toBytes(loginArguments);
        Request request = new Request();
        request.setType(0x1);
        request.setLength(payload.length);
        request.setBody(payload);
        //2.发送请求
        sendRequest(request);
        //3.获取服务器响应
        Response response = getResponse();
        System.out.println("[TCPClient] 读取到服务器响应！type: " + response.getType() + ", length: " + response.getLength());
        LoginResponse loginResponse = (LoginResponse) BinaryTool.fromBytes(response.getBody());
        return loginResponse.isOk();
    }


    public static void main(String[] args) throws IOException {
        TCPClient client = new TCPClient("127.0.0.1", 9090);
        boolean login = client.login("cyk", "123");
    }

}
